import { Component, OnInit, Inject, AfterViewChecked, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { AssetType } from '../../models/AssetType';
import { ITreeOptions, TreeComponent } from 'angular-tree-component';
import { TREE_ACTIONS, IActionMapping } from 'angular-tree-component';
import { AssetService } from '../../service/assetService';

@Component({
  templateUrl: './assettypeadd.html',
  styleUrls: ['./assettypeadd.css']
})
export class AssettypeaddComponent implements OnInit, AfterViewChecked {
  messages = {
    GDZCLBMC: '',
    assettypeName: ''
  };
  assetType: AssetType = {};
  options: ITreeOptions = {};
  nodes: any = [];
  assettypeName: string;
  typetree: boolean = false;
  @ViewChild(TreeComponent)
  private tree: TreeComponent;
  assetTypes: AssetType[];
  actionMapping: IActionMapping = {
    mouse: {
      click: (tree, node, $event) => {
        this.assettypeName = node.data.GDZCLBMC;
        this.assetType.sjgdzclb_DM = node.data.GDZCLB_DM;
        this.typetree = false;
      }
    }
  };
  constructor(
    private dialogRef: MatDialogRef<AssettypeaddComponent>,
    private assetService: AssetService,
    @Inject(MAT_DIALOG_DATA) public data: {assetTypes: AssetType[], nodes: any}
  ) {
    this.assetTypes = data.assetTypes;
    this.nodes = data.nodes;
    this.nodes.push(
    {GDZCLBMC: '无', GDZCLB_DM: 0}
    )
  }
  @ViewChild('assettypeForm')
  assettypeForm: NgForm;

  ngAfterViewChecked() {
    if (this.assettypeForm) {
      this.assettypeForm.valueChanges.subscribe(data => this.checkValidate());
    }
  }

  ngOnInit() {
    this.options = {displayField: 'GDZCLBMC', idField: 'GDZCLB_DM', actionMapping: this.actionMapping };
  }
  onSubmit() {
    this.checkValidate(true);
    if (this.assettypeForm.invalid) {
      // 触发mat的error
      this.assettypeForm.onSubmit(null);
      return false;
    }
    this.assetType.gdzclbmc = this.assetType.GDZCLBMC;
    this.assetService.insertAssetType(this.assetType).subscribe((res) => {
      this.dialogRef.close(res.res);
    });


  }
  checkValidate(isSubmit?: boolean) {
    const form = this.assettypeForm;

    for (const field in AssettypeaddComponent.ErrorMessages) {

      const control = form.controls[field];

      if (control && control.valid) {
        this.messages[field] = '';
      }
      if (control && (control.dirty || isSubmit) && !control.valid) {
        const messages = AssettypeaddComponent.ErrorMessages[field];
        if (control.errors) {
          this.messages[field] = messages[Object.keys(control.errors)[0]];
        }
      }

    }
  }

  showtypeTree() {
    this.typetree = !this.typetree;
  }
  hidetree() {
    this.typetree = false;
  }

  static ErrorMessages = {
    assettypeName: {
      required: '上级分类不能为空'
    },
    GDZCLBMC: {
      required: '分类名称不能为空'
    }
  };
}
